package com.management.controller;


import com.management.controller.info.AccountInfo;
import com.management.model.Account;
import com.management.model.Attach;
import com.management.service.AttachService;
import com.management.utils.OSSTemplate;
import com.management.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 龙世超
 * @since 2022-03-23
 */
@Api(tags = "附件相关")
@RestController
@RequestMapping("/attach")
public class AttachController {

    @Resource
    private OSSTemplate ossTemplate;

    @Resource
    private AttachService attachService;

    /**
     * 附件上传
     * @param fileName
     * @return
     * @throws IOException
     */
    @ApiOperation("附件上传")
    @GetMapping("/uploadFill")
    public Result uploadFill(MultipartFile fileName) throws IOException {

        String oldname = fileName.getOriginalFilename();
        String type = oldname.substring(oldname.lastIndexOf("."));
        String newName = "defectfile/"+System.currentTimeMillis()+type;
        String s = ossTemplate.uploadFile(newName, fileName.getInputStream());
        Attach attach = new Attach();

        attach.setAttachOldname(oldname);
        attach.setAttachFile(newName);
        attach.setFileSize(new BigDecimal(fileName.getSize()));
        attach.setMimeType(type.replace(".",""));
        attach.setIsPic(type.equals(".png")||type.equals(".jpg")?1:0);
        attach.setAttachDesc(s);
        AccountInfo principal = (AccountInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        attach.setCreateBy(principal.getAccountName());
        return attachService.AddAttach(attach);
    }

    /**
     * 附件下载
     * @param name
     * @return
     */
    @ApiOperation("附件下载")
    @GetMapping("/downloadFile")
    public Result downloadFile(String name){
        ossTemplate.downloadFile(name);
        return Result.getInstance().setMessage("下载成功");
    }
}

